<?php
/**
 * 
 * @author bqd
 *
 */
class ExtendedTreeBehavior extends ModelBehavior {
	var $options = array();
    function setup(&$model, $settings = array()) {
        $default = array(
			'lft'		=> 'lft',
			'rght'		=> 'rght',
			'parent'	=> 'parent_id',
		);

		if (!isset($this->__settings[$model->alias])) {
			$this->__settings[$model->alias] = $default;
		}
		
		$this->__settings[$model->alias] = am($this->__settings[$model->alias], $settings);
    }
	
	function transformToTree(&$model, $nodes) {
		if (count($nodes) == 1) {
			return $nodes;
		}
		// else
		for ($i = 0; $i < count($nodes); $i++) {
			if ($i == 0) {
				$nodes[$i]['depth'] = 0;
				continue;
			}
			for ($j = $i-1; $j >= 0; $j--) {
				if ($nodes[$i][$model->alias][$this->__settings[$model->alias]['lft']] > $nodes[$j][$model->alias][$this->__settings[$model->alias]['lft']] && $nodes[$i][$model->alias][$this->__settings[$model->alias]['rght']] < $nodes[$j][$model->alias][$this->__settings[$model->alias]['rght']]) {
					if (!isset($nodes[$j]['items'])) {
						$nodes[$j]['items'] = array();
					}
					
					$nodes[$i]['depth'] = $nodes[$j]['depth'] + 1;
					$nodes[$j]['items'][] = &$nodes[$i];
					break;
				}
			}
			
			if ($j == -1) {
				$nodes[$i]['depth'] = 0;
			}
		}
		
		$retVal = array();
		foreach ($nodes as &$item) {
			if ($item['depth'] == 0) {
				$retVal[] = $item;
			}
		}
		return $retVal;
	}
	
	function &getNode(&$stack, $parent_id) {
		$last_node = &$stack[count($stack)-1];
		if ($parent_id == $last_node[$model->alias]['id']) {
			return $last_node;
		} else {
			array_pop($stack);
			return $this->getNode($stack, $parent_id);
		}
	}
}
?>